﻿using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Admin.NET.Core;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq.Dynamic.Core;
using Microsoft.AspNetCore.Http;
using System.Text;
using System.Web;

namespace Admin.NET.Application
{
    /// <summary>
    /// 入库通知单服务
    /// </summary>
    [ApiDescriptionSettings("入库通知单", Name = "WmsOrder", Order = 100)]
    [Route("api/[Controller]")]
    public class WmsOrderService : IWmsOrderService, IDynamicApiController, ITransient
    {
        private readonly IRepository<WmsOrder,MasterDbContextLocator> _wmsOrderRep;
        private readonly IRepository<SysDictType, MasterDbContextLocator> _sysDictTypeRep;
        private readonly IRepository<SysDictData, MasterDbContextLocator> _sysDictDataRep;
        private readonly ISysExcelTemplateService _sysExcelTemplateService;
        private readonly static object _lock = new();
        private readonly IRepository<WmsOrderType, MasterDbContextLocator> _wmsOrderTypeRep;
        private readonly IRepository<WmsOrderDetails, MasterDbContextLocator> _wmsOrderDetailsRep;
        private readonly IRepository<WmsPlace, MasterDbContextLocator> _wmsPlaceRep;

        public WmsOrderService(
            IRepository<WmsOrder,MasterDbContextLocator> wmsOrderRep
            ,IRepository<SysDictType, MasterDbContextLocator> sysDictTypeRep
            ,IRepository<SysDictData, MasterDbContextLocator> sysDictDataRep
            ,ISysExcelTemplateService sysExcelTemplateService
            ,IRepository<WmsOrderType, MasterDbContextLocator> wmsOrderTypeRep
            ,IRepository<WmsOrderDetails, MasterDbContextLocator> wmsOrderDetailsRep
            ,IRepository<WmsPlace, MasterDbContextLocator> wmsPlaceRep
        )
        {
            _wmsOrderRep = wmsOrderRep;
            _sysDictTypeRep = sysDictTypeRep;
            _sysDictDataRep = sysDictDataRep;
            _sysExcelTemplateService = sysExcelTemplateService;
            _wmsOrderTypeRep = wmsOrderTypeRep;
            _wmsOrderDetailsRep = wmsOrderDetailsRep;
            _wmsPlaceRep = wmsPlaceRep;
        }

        /// <summary>
        /// 分页查询单据表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("page")]
        public async Task<PageResult<WmsOrderOutput>> Page([FromQuery] WmsOrderSearch input)
        {
            var wmsOrders = await _wmsOrderRep.DetachedEntities
                                     .Where(!string.IsNullOrEmpty(input.NO), u => EF.Functions.Like(u.NO, $"%{input.NO.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.SourceBillNo), u => EF.Functions.Like(u.SourceBillNo, $"%{input.SourceBillNo.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.Vendorcode), u => EF.Functions.Like(u.Vendorcode, $"%{input.Vendorcode.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.Vendorname), u => EF.Functions.Like(u.Vendorname, $"%{input.Vendorname.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.Companyname), u => EF.Functions.Like(u.Companyname, $"%{input.Companyname.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.WarehouseKeepername), u => EF.Functions.Like(u.WarehouseKeepername, $"%{input.WarehouseKeepername.Trim()}%"))
                                     .Where(input.TradeMode != null, u => u.TradeMode == input.TradeMode)
                                     .Where(!string.IsNullOrEmpty(input.WarehouseCentername), u => EF.Functions.Like(u.WarehouseCentername, $"%{input.WarehouseCentername.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.StoreRoomname), u => EF.Functions.Like(u.StoreRoomname, $"%{input.StoreRoomname.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.DeclarationCode), u => EF.Functions.Like(u.DeclarationCode, $"%{input.DeclarationCode.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.Majorname), u => EF.Functions.Like(u.Majorname, $"%{input.Majorname.Trim()}%"))
                                     .OrderBy(PageInputOrder.OrderBuilder<WmsOrderSearch>(input))
                                     .ProjectToType<WmsOrderOutput>()
                                     .ToADPagedListAsync(input.PageNo, input.PageSize);
            return wmsOrders;
        }

        /// <summary>
        /// 获取单据明细
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("PageDetail")]
        public async Task<PageResult<WmsOrderDetailOutput>> PageDetail([FromQuery] PageDetailInput input)
        {
            var wmsOrders = await _wmsOrderDetailsRep.DetachedEntities
                                     .Where(input.Id != null, u => u.OrderId == input.Id)
                                     .ProjectToType<WmsOrderDetailOutput>()
                                     .ToADPagedListAsync(input.PageNo, input.PageSize);
            return wmsOrders;
        }

        /// <summary>
        /// 批量下发入库单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("DistributeInOrder")]
        [UnitOfWork]
        public async Task DistributeInOrder(DistributeInOrderInput input)
        {
            // 查询所有单据状态为“撤回”或者“未下发”的信息
            var wmsOrderList = await _wmsOrderRep.DetachedEntities.Where(u => input.Id.Contains(u.Id)
            && (u.OrderStatus == OrderStatusEnum.CHEHUI || u.OrderStatus == OrderStatusEnum.WEIXIAFA)).ProjectToType<WmsOrder>().ToListAsync();
            if (wmsOrderList.Count <= 0) throw Oops.Oh(errorMessage: "无下发工单！");
            //因为不知道下发单据时，一个托盘放几个明细，所以无法判断库位是否不足，在入库提交时判断
            lock (_lock)
            {
                // 修改单据状态
                foreach (var order in wmsOrderList)
                {
                    // 更新单据状态为“已下发”
                    order.OrderStatus = OrderStatusEnum.YIXIAFA;
                    _wmsOrderRep.UpdateAsync(order);
                }
            }
        }


        /// <summary>
        /// 不分页查询单据表列表
        /// </summary>
        /// <param name="input">单据表查询参数</param>
        /// <returns>(单据表)实例列表</returns>
        [HttpGet("listNonPage")]
        public async Task<List<WmsOrderOutput>> ListNonPageAsync([FromQuery] WmsOrderSearchNonPage input)
        {
            var pNO = input.NO?.Trim() ?? "";
            var pSourceBillNo = input.SourceBillNo?.Trim() ?? "";
            var pVendorcode = input.Vendorcode?.Trim() ?? "";
            var pVendorname = input.Vendorname?.Trim() ?? "";
            var pCompanyname = input.Companyname?.Trim() ?? "";
            var pWarehouseKeepername = input.WarehouseKeepername?.Trim() ?? "";
            var pTradeMode = input.TradeMode;
            var pWarehouseCentername = input.WarehouseCentername?.Trim() ?? "";
            var pStoreRoomname = input.StoreRoomname?.Trim() ?? "";
            var pDeclarationCode = input.DeclarationCode?.Trim() ?? "";
            var pMajorname = input.Majorname?.Trim() ?? "";
            var wmsOrders = await _wmsOrderRep.DetachedEntities
                .Where(!string.IsNullOrEmpty(pNO), u => EF.Functions.Like(u.NO, $"%{pNO}%")) 
                .Where(!string.IsNullOrEmpty(pSourceBillNo), u => EF.Functions.Like(u.SourceBillNo, $"%{pSourceBillNo}%")) 
                .Where(!string.IsNullOrEmpty(pVendorcode), u => EF.Functions.Like(u.Vendorcode, $"%{pVendorcode}%")) 
                .Where(!string.IsNullOrEmpty(pVendorname), u => EF.Functions.Like(u.Vendorname, $"%{pVendorname}%")) 
                .Where(!string.IsNullOrEmpty(pCompanyname), u => EF.Functions.Like(u.Companyname, $"%{pCompanyname}%")) 
                .Where(!string.IsNullOrEmpty(pWarehouseKeepername), u => EF.Functions.Like(u.WarehouseKeepername, $"%{pWarehouseKeepername}%")) 
                .Where(pTradeMode != null, u => u.TradeMode == pTradeMode)
                .Where(!string.IsNullOrEmpty(pWarehouseCentername), u => EF.Functions.Like(u.WarehouseCentername, $"%{pWarehouseCentername}%")) 
                .Where(!string.IsNullOrEmpty(pStoreRoomname), u => EF.Functions.Like(u.StoreRoomname, $"%{pStoreRoomname}%")) 
                .Where(!string.IsNullOrEmpty(pDeclarationCode), u => EF.Functions.Like(u.DeclarationCode, $"%{pDeclarationCode}%")) 
                .Where(!string.IsNullOrEmpty(pMajorname), u => EF.Functions.Like(u.Majorname, $"%{pMajorname}%")) 
            .OrderBy(PageInputOrder.OrderNonPageBuilder(input))
            .ProjectToType<WmsOrderOutput>()
            .ToListAsync();
            return wmsOrders;
        }


        /// <summary>
        /// 增加单据表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task Add(AddWmsOrderInput input)
        {
            // 查询单据小类是“生产入库”的Id
            var wmsOrderType = await _wmsOrderTypeRep.FirstOrDefaultAsync(z => z.Name.Contains("生产入库"));
            var wmsOrder = input.Adapt<WmsOrder>();
            wmsOrder.SOID = 66666;
            wmsOrder.OrderLargeCategory = wmsOrderType != null ? wmsOrderType.Pid : 0;
            wmsOrder.OrderSubclass = wmsOrderType != null ? wmsOrderType.Id : 0;
            wmsOrder.OrderStatus = OrderStatusEnum.WEIXIAFA;
            await _wmsOrderRep.InsertAsync(wmsOrder);
        }

        /// <summary>
        /// 删除单据表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task Delete(DeleteWmsOrderInput input)
        {
            var wmsOrder = await _wmsOrderRep.FirstOrDefaultAsync(u => u.Id == input.Id);
            await _wmsOrderRep.DeleteAsync(wmsOrder);
        }

        /// <summary>
        /// 更新单据表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("edit")]
        public async Task Update(UpdateWmsOrderInput input)
        {
            var isExist = await _wmsOrderRep.AnyAsync(u => u.Id == input.Id, false);
            if (!isExist) throw Oops.Oh(ErrorCode.D3000);

            var wmsOrder = input.Adapt<WmsOrder>();
            await _wmsOrderRep.UpdateAsync(wmsOrder,ignoreNullValues:true);
        }

        /// <summary>
        /// 获取单据表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("detail")]
        public async Task<WmsOrderOutput> Get([FromQuery] QueryeWmsOrderInput input)
        {
            return (await _wmsOrderRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id)).Adapt<WmsOrderOutput>();
        }

        /// <summary>
        /// 获取单据表列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("list")]
        public async Task<List<WmsOrderOutput>> List([FromQuery] WmsOrderInput input)
        {
            return await _wmsOrderRep.DetachedEntities.ProjectToType<WmsOrderOutput>().ToListAsync();
        }    
         /// <summary>
        /// Excel模板导入单据表功能
        /// </summary>
        /// <param name="file">Excel模板文件</param>
        /// <param name="importExcelType">Excel导入方式</param>
        /// <returns>导入的记录数</returns>
        [HttpPost("fromExcel")]
        public async Task<int> FromExcelAsync(IFormFile file, [FromQuery] ImportExcelType importExcelType)
        {
            int size = 200;
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WmsOrder", "v2");
            if (excelTemplate == null) throw Oops.Oh(ErrorCode.Excel002);
            var keys = excelTemplate.UnionUniqueFields.Split(",") ?? Array.Empty<string>();
            for (var i = 0; i < keys.Length; i++) 
            {
                keys[i] = keys[i]?.Trim() ?? string.Empty;
            }
            ExcelUtil.FromExcel(file, excelTemplate.HeadStartLine, excelTemplate.DataStartLine, out List<string> headers, out List<List<object?>> data, out string sheetName);
            List<WmsOrderOutput> wmsOrderList = DataConvertUtil.ToObjectList(headers, data, sheetName, keys, excelTemplate?.DataStartLine ?? 2, out Dictionary<string, WmsOrderOutput> dict);
            List<Dictionary<string, object>> uniqueKeyValueDictList = wmsOrderList.ParseUniqueKeyValueDictList(keys.ToList(), excelTemplate?.DataStartLine ?? 2, sheetName);
            var filters = DataConvertUtil.GetExpressionListByUniqueDict<WmsOrder>(keys.ToList(), uniqueKeyValueDictList, size);
            var selectKeys = keys.ToList();
            if(!selectKeys.Contains("Id")) selectKeys.Add("Id");
            var selector = DataConvertUtil.GetSelectExpressionListByUniqueDict<WmsOrder, WmsOrderOutput>(selectKeys);
            List<WmsOrder> updates = new();
            List<WmsOrder> adds = new();

            lock (_lock)
            {
                foreach (var filter in filters)
                {
                    var wmsOrderExistSubList = _wmsOrderRep.Where(filter).Select(selector).ToList();
                    wmsOrderExistSubList.ForEach(x => 
                    {
                        var k = DataConvertUtil.GetKey(x, keys);
                        if (dict.ContainsKey(k)) dict[k].Id = x.Id;
                    });
                }
                foreach (var wmsOrder in wmsOrderList) 
                {
                    if (wmsOrder.Id > 0)
                    {
                        if (importExcelType == ImportExcelType.ADD_AND_UPDATE) updates.Add(wmsOrder.Adapt<WmsOrder>());
                    }
                    else 
                    {
                        adds.Add(wmsOrder.Adapt<WmsOrder>());
                    }
                }

                if (importExcelType == ImportExcelType.ADD_AND_UPDATE) updates.ForEach(x => _wmsOrderRep.Update(x));
                

                var maxId = _wmsOrderRep.DetachedEntities.OrderByDescending(x => x.Id).Select(x => x.Id).FirstOrDefault();
                adds.ForEach(x => x.Id = ++maxId);    
                Db.GetDbContext().Set<WmsOrder>().AddRange(adds);  
                Db.GetDbContext().SaveChanges();
               
            }
            await Task.CompletedTask;
            return adds.Count;
        }

        /// <summary>
        /// 根据版本下载单据表的Excel导入模板
        /// </summary>
        /// <param name="version">模板版本</param>
        /// <returns>下载的模板文件</returns>
        [HttpGet("downloadExcelTemplate")]
        public async Task<IActionResult> DownloadExcelTemplate([FromQuery] string version)
        {
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WmsOrder", version);
            if (excelTemplate == null) throw Oops.Oh(ErrorCode.Excel002);
            var path = Path.Combine(@"\", excelTemplate.TemplateFileName);
            Stream ms = FileUtil.Download(path, excelTemplate.TemplateFileName);
            var fileName = HttpUtility.UrlEncode($"{excelTemplate.Name}导入模板.xlsx", Encoding.GetEncoding("UTF-8"));
            return new FileStreamResult(ms, "application/octet-stream") { FileDownloadName = fileName };
        }
        /// <summary>
        /// 根据单据表查询参数导出Excel
        /// </summary>
        /// <param name="input">单据表查询参数</param>
        /// <returns>导出的Excel文件</returns>
        [HttpGet("toExcel")]
        public async Task<IActionResult> ToExcelAsync([FromQuery] WmsOrderSearchNonPage input)
        {
            var wmsOrderList = await ListNonPageAsync(input);
            MemoryStream ms = new();
            DataConvertUtil.ToExcelData(wmsOrderList, _sysDictTypeRep, _sysDictDataRep, out List<string> headers, 
                out List<List<object>> data, out string sheetName);
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WmsOrder", "v1");
            if (excelTemplate != null)
            {
                ExcelUtil.ToExcel(excelTemplate.TemplateFileName, headers, data, sheetName, excelTemplate.HeadStartLine, excelTemplate.DataStartLine, ms);
            }
            else 
            {
                ExcelUtil.ToExcel(headers, data, sheetName, ms);
            }
            ms.Position = 0;
            var fileName = HttpUtility.UrlEncode($"{sheetName}[{DateTimeOffset.Now:yyyy-MM-dd}].xlsx", Encoding.GetEncoding("UTF-8"));
            return new FileStreamResult(ms, "application/octet-stream") { FileDownloadName = fileName };
        }
    }
}
